const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const _ = db.command;
const ELEMENT_NUMBER = 10;
const SUPPORTED_STATUS = new Set(["Draft", "Published", "Withdraw", "All"]);

const normalizeStatus = value => {
  if (typeof value !== "string") return "";
  const v = value.trim().toLowerCase();
  if (v === "draft") return "Draft";
  if (v === "published") return "Published";
  if (v === "withdraw") return "Withdraw";
  if (v === "all") return "All";
  return "";
};

const normalizeBoolean = value => {
  if (typeof value === "boolean") return value;
  if (typeof value === "string") {
    const trimmed = value.trim().toLowerCase();
    if (trimmed === "true") return true;
    if (trimmed === "false") return false;
  }
  if (typeof value === "number") {
    return value !== 0;
  }
  return false;
};

module.exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;

  const tableRaw = event && event.tableNumber;
  const tableNumber =
    Number.isFinite(Number(tableRaw)) && Number(tableRaw) > 0
      ? Math.floor(Number(tableRaw))
      : 1;

  const statusRaw = event && event.status;
  const requestedStatus = normalizeStatus(statusRaw);

  const effectiveStatus = SUPPORTED_STATUS.has(requestedStatus)
    ? requestedStatus
    : "All";
  //构造查询条件
  const whereClause = { PublisherOpenID: openID };

  if (effectiveStatus === "Draft") {
    whereClause.Status = "Draft";
  } else if (effectiveStatus === "Published") {
    whereClause.Status = "Published";
  } else if (effectiveStatus === "Withdraw") {
    whereClause.Status = "Withdraw";
  }
  // effectiveStatus === "All" 时不过滤 Status
  const orderField =
    effectiveStatus === "Published" ? "ActivityPublishTime" : "_id";

  const offset = (tableNumber - 1) * ELEMENT_NUMBER;

  const actRes = await db
    .collection("Activity_Information")
    .where(whereClause)
    .orderBy(orderField, "desc")
    .skip(offset)
    .limit(ELEMENT_NUMBER)
    .get();

  const activities = await Promise.all(
    (actRes.data || []).map(async item => {
      const groupRes = await db
        .collection("Activity_Group_Information")
        .where({ ActivityID: item._id })
        .orderBy("GroupStartTime", "asc")
        .get();
      return {
        activityID: item._id,
        activityName: item.ActivityName,
        activityImage: item.ActivityImageURL,
        activityStartTime: (groupRes.data || []).map(g => g.GroupStartTime),
        activityLocation: item.ActivityLocation,
        status: item.Status || ""
      };
    })
  );

  return { activities };
};
